<template>
  <div class="ElectricControl flexScroll">
    <!-- 公用表头组件 -->
    <el-card class="box-card">
      <CommonForm />
    </el-card>
    <!-- 公共导航 -->
    <el-card>
      <NavTab />
    </el-card>
    <!-- 表单值 -->
    <el-card class="box-card">
      <!-- 表单查询类 -->
      <el-form ref="dataInfo" label-width="100px" :model="dataInfo">
        <div class="flex-sb">
          <el-form-item v-for="(v, i) of settingJson.ElectricControl.serBox" :key="i" :label="v.label">
            <!-- input框 -->
            <el-input v-if="v.type == 'input'" v-model="dataInfo[v.prop]" clearable placeholder="" />
            <!-- 级联 -->
            <el-cascader
              v-if="v.type == 'cascader'"
              v-model="dataInfo[v.prop]"
              clearable
              :options="v.options"
              :props="{ checkStrictly: true }"
              @change="handleChange($event, v.prop)"
            />
          </el-form-item>

          <div class="flex-sb" style="margin-bottom: 18px">
            <el-button @click="reset">
              <vui-icon icon="refresh-line" />
              重置
            </el-button>
            <el-button type="primary" @click="queryFuc">
              <vui-icon icon="search-2-line" />
              查询
            </el-button>
          </div>
          <el-form-item>
            <el-button :disabled="formData.length == 0" :type="StatusName == '发布数据' ? 'primary' : 'danger'" @click="dataRelease(StatusName)">
              {{ StatusName }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
      <!-- 表单 -->
      <Table :form-data="formData" :form-string="'ElectricControl'" />
    </el-card>
    <el-dialog v-model="releaseDialog" title="操作确认" width="50%">
      <ReleaseDialog v-if="releaseDialog" @confirm="confirm" />
    </el-dialog>
  </div>
</template>
<script>
  import NavTab from '@/project/bqms/components/NavTab.vue'
  import ReleaseDialog from '@bqms/components/ReleaseDialog.vue'
  import CommonForm from '@bqms/components/ComTable.vue'
  import settingJson from '@bqms/common/index'
  import { getList } from '../api/home'
  import { GFCD } from '@/utils/utils'
  import Table from '@bqms/components/Table.vue'

  export default {
    name: 'ElectricControl',
    components: {
      CommonForm,
      Table,
      ReleaseDialog,
      NavTab,
    },
    data() {
      return {
        settingJson: settingJson,
        // 获取table内容数据
        dataInfo: {
          EQUIPMENT_ID: '', //设备编号
          TYPE_ID: '', //设备类型
        },
        formData: [],
        OneData: {},
        releaseDialog: false,
        someBoolean: false,
        saveData: [],
        StatusName: '',
        DOCNO: '',
        name: 'ElectricControl',
        options: [],
      }
    },
    watch: {
      DOCNO: {
        deep: true,
        handler() {
          this.formData = []
          this.dataInfo = {}
        },
      },
    },
    created() {
      this.formTH = this.settingJson.ElectricControl.formData
      this.postUrl = `${GFCD('bqms').domain}${GFCD('bqms').baseUrl}`
      if (this.$store.getters['bqmsData/HeaderTable']['ECU_ISSUE'] == 'Y') {
        this.StatusName = '撤销发布'
      } else {
        this.StatusName = '发布数据'
      }
      this.formTH.forEach((v) => {
        if (this.$store.getters['bqmsData/HeaderTable']['ECU_ISSUE'] == 'Y') {
          if (v.type == 'button' || v.type == 'switch' || v.type == 'select' || v.type == 'input') {
            v.isDisable = true
          }
        }
      })
      this.Cascader()
      this.eventInit()
    },
    activated() {
      this.DOCNO = this.$store.getters['bqmsData/budgetSheetNum']
    },

    methods: {
      // 重置
      reset() {
        this.dataInfo = {}
        this.query()
      },
      handleChange(value, key) {
        if (value != null) {
          this.dataInfo[key] = value[value.length - 1]
        }
      },
      // 级联下拉接口
      Cascader() {
        let method = 'bqms.type.manage.query'
        getList(this.postUrl, {
          method,
          data: JSON.stringify({
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 99999,
            // PARAENT_TYPE_ID: id,
          }),
        })
          .then((res) => {
            if (res.code == '00000') {
              console.log('级联接口', res.data[method].data)
              this.srcArr = res.data[method].data
              res.data[method].data.forEach((item) => {
                if (item.PARAENT_TYPE_ID == 0) {
                  this.options.push({
                    parentId: item.PARAENT_TYPE_ID,
                    value: item.TYPE_ID,
                    label: item.TYPE_NAME,
                    children: [],
                  })
                }
              })
              this.options.forEach((it) => {
                it.children = this.getChildren(it.value, this.srcArr)
              })

              this.settingJson.ElectricControl.serBox.forEach((v) => {
                if (v.type == 'cascader' && v.label == '设备类型：') {
                  v.options = this.options
                }
              })
            }
          })
          .catch((e) => {
            console.log('e', e)
          })
      },
      // 处理级联--递归
      getChildren(tId, srcArr) {
        let children = []
        srcArr.forEach((item) => {
          if (item.PARAENT_TYPE_ID == tId) {
            children.push({
              parentId: item.PARAENT_TYPE_ID,
              value: item.TYPE_ID,
              label: item.TYPE_NAME,
              children: [],
            })
          }
        })
        if (children.length == 0) {
          return null
        }
        children.forEach((item) => {
          item.children = this.getChildren(item.value, this.srcArr)
        })
        return children
      },
      // 发布或者撤销发布按钮
      dataRelease() {
        if (this.$store.getters['bqmsData/HeaderTable']['ECU_ISSUE'] == 'Y') {
          // 完成状态---撤销发布
          this.ReleaseModel('是否撤销发布？', () => {
            this.releaseFuc('bqms.common.reverseRelease')
          })
        } else {
          // 发布数据
          this.ReleaseModel('是否确认发布？', () => {
            this.someBoolean = this.saveData.some(function (item) {
              return item.INVERTERB_RAND == '' || item.ECU_BRAND == ''
            })
            if (this.someBoolean) {
              this.$message({
                message: '请把表格中数据填写完全！',
                type: 'warning',
              })
              return
            }
            this.releaseFuc('bqms.common.sp.release')
          })
        }
      },
      // 发布或者撤销发布模态框
      ReleaseModel(text, cb) {
        this.$confirm(text, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            if (cb) cb()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            })
          })
      },
      // 发布数据接口
      releaseFuc(method) {
        getList(this.postUrl, {
          method,
          data: JSON.stringify({
            TYPE: 'ECU_ISSUE', //单机电控发布接口
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'], //单号
          }),
        }).then((res) => {
          if (res.code == '00000') {
            if (res.code == '00000') {
              if (method == 'bqms.common.sp.release') {
                this.$message({
                  message: '数据发布成功',
                  type: 'success',
                })
              } else if (method == 'bqms.common.reverseRelease') {
                this.$message({
                  message: '撤销发布成功',
                  type: 'success',
                })
              }

              // 重新调用通用单号
              this.$pub(`topFormData`, true)

              this.releaseDialog = false
            }
          }
        })
      },

      // $sub返回
      eventInit() {
        //表格所有数据

        this.$sub(`TableData${this.name}`, (data) => {
          this.saveData = []
          data[0].forEach((item) => {
            this.saveData.push({
              OLD_WHETHER: item.OLD_WHETHER, //是否利旧
              ECU_BRAND: item.ECU_BRAND, //单机电控品牌
              ECU_PRICE: item.ECU_PRICE, //单机电控价格
              INVERTERB_RAND: item.INVERTERB_RAND, //变频器品牌
              INVERTERP_RICE: item.INVERTERP_RICE, //变频器价格
              DOCNO: this.$store.getters['bqmsData/budgetSheetNum'], //订单号
              VERSION: this.$store.getters['bqmsData/HeaderTable'].VERSION,
              EQUIPMENT_ID: item.EQUIPMENT_ID, //设备编号
            })
          })
        })
        this.$sub(`TableSaveOne${this.name}`, (data) => {
          this.OneData = {
            OLD_WHETHER: data[0].OLD_WHETHER, //是否利旧
            ECU_BRAND: data[0].ECU_BRAND, //单机电控品牌
            ECU_PRICE: data[0].ECU_PRICE, //单机电控价格
            INVERTERB_RAND: data[0].INVERTERB_RAND, //变频器品牌
            INVERTERP_RICE: data[0].INVERTERP_RICE, //变频器价格
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'], //订单号
            VERSION: this.$store.getters['bqmsData/HeaderTable'].VERSION,
            EQUIPMENT_ID: data[0].EQUIPMENT_ID, //设备编号

            EQUIPMENT_TYPE: data[0].EQUIPMENT_TYPE, //

            MOTOR_POWER: data[0].MOTOR_POWER, //
          }
          if (data[0].ECU_BRAND == '' || data[0].ECU_PRICE == '' || data[0].INVERTERB_RAND == '' || data[0].INVERTERP_RICE == '') {
            this.$message({
              message: '单机电控品牌价格、变频器！',
              type: 'warning',
            })
            return
          }
          this.saveDataFuc(this.OneData, true)
        })
        // 改变标题头数据；额
        this.$sub(`changeHeadere`, (data) => {
          if (data) {
            if (this.$store.getters['bqmsData/HeaderTable']['ECU_ISSUE'] == 'Y') {
              this.StatusName = '撤销发布'
            } else {
              this.StatusName = '发布数据'
            }
            this.formTH.forEach((v) => {
              if (this.$store.getters['bqmsData/HeaderTable']['ECU_ISSUE'] == 'Y') {
                if (v.type == 'button' || v.type == 'switch' || v.type == 'select' || v.type == 'input') {
                  v.isDisable = true
                }
              } else {
                if (v.type == 'button' || v.type == 'switch' || v.type == 'select' || v.type == 'input') {
                  v.isDisable = false
                }
              }
            })
          }
        })
      },
      // 保存电控数据接口
      saveDataFuc(data, B) {
        let method = 'bqms.single.electrical.control.update'
        getList(this.postUrl, {
          method,
          data: JSON.stringify(data),
        }).then((res) => {
          if (res.code == '00000') {
            if (B) {
              this.$message({
                message: '数据保存成功',
                type: 'success',
              })
              this.query()
            }
          }
        })
      },
      queryFuc() {
        this.query(() => {
          this.brandFuc('DJDK')
          this.brandFuc('BPQ')
        })
      },

      // 查询列表
      query(cb) {
        let method = 'quotationServiceImpl.query'
        if (this.$store.getters['bqmsData/HeaderTable'].BASIC_DATA_ISSUE == 'N') return this.$message.error('基础数据未发布')
        getList(this.postUrl, {
          method,
          data: JSON.stringify({
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 99999,
            OUT_SOURCE: 'N',
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'], //订单号
            ...this.dataInfo,
          }),
        }).then((res) => {
          if (res.code == '00000') {
            res.data.forEach((row) => {
              row.ECU_PRICE = Math.floor(row.ECU_PRICE * 100) / 100
              row.INVERTERP_RICE = Math.floor(row.INVERTERP_RICE * 100) / 100
            })
            this.formData = res.data
            if (cb) cb()
          }
        })
      },
      // 单机电控品牌下拉选接口
      brandFuc(data) {
        let method = 'bqms.brand.query'
        getList(this.postUrl, {
          method,
          data: JSON.stringify({
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 99999,
            TYPE_ID: data,
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.formTH.forEach((v) => {
              if (v.type == 'select' && v.label == '单机电控品牌' && data == 'DJDK') {
                v.options = []
                res.data[method].data.forEach((vv) => {
                  v.options.push({
                    value: vv.BRAND_ID,
                    label: vv.BRAND_NAME,
                    PRICE_UNTAX: vv.PRICE_UNTAX,
                  })
                })
              }
              if (v.type == 'select' && v.label == '变频器品牌' && data == 'BPQ') {
                v.options = []
                res.data[method].data.forEach((vv) => {
                  v.options.push({
                    value: vv.BRAND_ID,
                    label: vv.BRAND_NAME,
                    PRICE_UNTAX: vv.PRICE_UNTAX,
                  })
                })
              }
            })
          }
        })
      },
    },
  }
</script>

<style lang="scss">
  @import '@bqms/static/scss/Common.scss';
  .ElectricControl {
    width: calc(100% - 40px);
    padding: 20px;
    .flex-sb {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    // 列表页查询按钮
    .sercBtn {
      .el-form-item__content {
        position: absolute;
        right: 40px;
      }
    }
  }
</style>
